package com.bona.service.report;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bona.dao.common.BaseDao;
import com.bona.dao.report.ReportHeadDao;
import com.bona.dao.report.ReportItemDao;
import com.bona.dao.report.ReportParamDao;
import com.bona.model.report.ReportHeadModel;
import com.bona.model.report.ReportItemModel;
import com.bona.model.report.ReportParamModel;
import com.bona.service.common.BaseService;
import com.bona.util.common.StringUtil;
import com.bona.util.common.UUIDGenerator;

@Service("reportHeadService")
@Transactional
public class ReportHeadService extends BaseService {

	@Autowired
	private ReportHeadDao reportHeadDao;
	@Autowired
	private ReportItemDao reportItemDao;
	@Autowired
	private ReportParamDao reportParamDao;
	
	@Override
	public BaseDao getDao() {
		return reportHeadDao;
	}

	/**
	 * 添加或更新分组信息
	 * @param model
	 */
	public void addOrUpdate(ReportHeadModel model) {
		
		if (StringUtil.isEmpty(model.getId())) {	// 新增分组信息
			model.setId(UUIDGenerator.generate());
			reportHeadDao.add(model);
			for (ReportItemModel item: model.getReportItemList()) {
				item.setId(UUIDGenerator.generate());
				item.setCgrheadId(model.getId());
				reportItemDao.add(item);
			}
			for (ReportParamModel param: model.getReportParamList()) {
				param.setId(UUIDGenerator.generate());
				param.setCgrheadId(model.getId());
				param.setCreateBy(model.getCreateBy());
				param.setCreateName(model.getCreateName());
				param.setCreateDate(model.getCreateDate());
				reportParamDao.add(param);
			}
			return;
		}
		reportHeadDao.update(model);
		// 解除报表项和报表之间关系
		ReportItemModel reportItemModel = new ReportItemModel();
		reportItemModel.setCgrheadId(model.getId());
		reportItemDao.delete(reportItemModel);
		// 解除报表参数和报表之间关系
		ReportParamModel reportParamModel = new ReportParamModel();
		reportParamModel.setCgrheadId(model.getId());
		reportParamDao.delete(reportParamModel);
		
		for (ReportItemModel item: model.getReportItemList()) {
			item.setId(UUIDGenerator.generate());
			item.setCgrheadId(model.getId());
			reportItemDao.add(item);
		}
		for (ReportParamModel param: model.getReportParamList()) {
			param.setId(UUIDGenerator.generate());
			param.setCgrheadId(model.getId());
			param.setCreateBy(model.getCreateBy());
			param.setCreateName(model.getCreateName());
			param.setCreateDate(model.getCreateDate());
			param.setUpdateBy(model.getUpdateBy());
			param.setUpdateName(model.getUpdateName());
			param.setUpdateDate(model.getUpdateDate());
			reportParamDao.add(param);
		}
	}

}
